package com.e.dianshang.controller;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.e.dianshang.service.UserService;
import com.e.dianshang.utils.BusinessException;
import com.e.dianshang.utils.JsonResult;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TOOD
 * @ClassName: SMSController
 * @Author: ${陈柯宇}
 * Date: 2020/10/21 10:07
 * @Version: 1.0
 */
@RestController
@Api(value = "发送验证码接口",tags = "验证码")
public class SMSController {

    @Resource
    UserService userService;

    //java要操作redis,是借助于RedisTemplate
    @Resource
    RedisTemplate<String,String> redisTemplate;

    @ApiOperation(value = "用户注册发送验证码的接口")
    @ApiImplicitParam(name = "phone",value = "当前用户电话号码",required = true,
            dataType = "String",paramType = "query")
    @RequestMapping(value = "/send",method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Map send(@RequestParam(value = "phone") String phone) throws BusinessException {
        JsonResult jsonResult=new JsonResult();
        String byPhone = userService.findByPhone(phone);
        if (byPhone!=null && !byPhone.equals("") ){
            throw new BusinessException("该用户已经注册，请更换或直接登录");
//            jsonResult.setCode();
        }
        //判断该手机号是否已经注册
        //是，提示信息或直接登录；否，可以注册，调用阿里云的短信接口，实现发送
        //短信，接收阿里云的返回数据，根据返回值给用户提示
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "LTAI4GFeFDiGNDf454M5taHK", "xybJOkQwRu9742s3cXoRWXFX4Z6HTi");
        IAcsClient client = new DefaultAcsClient(profile);

        //固定写法
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", "cn-hangzhou");
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "三四商城");
        request.putQueryParameter("TemplateCode", "SMS_204976083");

        //生成4位随机数验证码(1-9)
        String code="";
        for (int i=0;i<4;i++){
            code+=(int)(Math.random()*9+1);
        }
        // 给阿里云短信模板中的${code}赋值，json格式
        request.putQueryParameter("TemplateParam", "{'code':"+code+"}");
        try {
            CommonResponse response = client.getCommonResponse(request);
            // 获取的验证码数据,
            String data = response.getData();
            //{"Message":"OK","RequestId":"CBC83055-A113-483A-91B2-0E4C56CCC643","BizId":"790710603115763709^0","Code":"OK"}

            ObjectMapper mapper = new ObjectMapper();
            Map<String, Object> tmpMap=mapper.readValue(data, Map.class);
            if("OK".equals(tmpMap.get("Code"))){
                jsonResult.setCode("1");
                jsonResult.setMsg("验证码发送成功");

                // 将数据保存在redis服务器上, 15分钟有效
                //1.利用RedisTemplate绑定要操作的数据类型,生成对应的操作符对象
                ValueOperations<String, String> operations = redisTemplate.opsForValue();
                //2.利用操作符对象对该类型数据赋值
                // 设置生存时间
                operations.set("ds:"+phone,code,15, TimeUnit.MINUTES);
            }else{
                jsonResult.setCode("0");
                jsonResult.setMsg("验证码发送失败,请检查手机号或稍后再试");
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        return  jsonResult.getValues();
    }
}
